﻿using Microsoft.CodeAnalysis.CSharp.Scripting;
using System.Threading.Tasks;

namespace Cyss.Core.Helper
{
    /// <summary>
    /// 执行字符串表达式帮助类
    /// </summary>
    public class EvaluatorHelper
    {

        private static Jint.Engine jsEngine { set; get; }


        /// <summary>
        /// 字符串表达式(性能不好)
        /// </summary>
        /// <param name="strExpression"></param>
        /// <returns></returns>
        public static async Task<T> EvalAsync<T>(string strExpression)
        {
            return await CSharpScript.EvaluateAsync<T>(strExpression);
        }

        /// <summary>
        /// 字符串表达式(性能不好)
        /// </summary>
        /// <param name="strExpression"></param>
        /// <returns></returns>
        public static async Task<object> EvalAsync(string strExpression)
        {
            return await CSharpScript.EvaluateAsync(strExpression);
        }

        public static int? JSEvalInt(string strExpression)
        {
            if (jsEngine==null)
            {
                jsEngine=new Jint.Engine();
            }
            var jsValue = jsEngine.Execute(strExpression).GetCompletionValue();
            if (jsValue.IsNull() || jsValue.IsUndefined())
            {
                return null;
            }
            return (int)jsValue.AsNumber();
        }

        public static bool? JSEvalBool(string strExpression)
        {
            if (jsEngine==null)
            {
                jsEngine=new Jint.Engine();
            }
            var jsValue = jsEngine.Execute(strExpression).GetCompletionValue();
            if (jsValue.IsNull() || jsValue.IsUndefined())
            {
                return null;
            }
            return jsValue.AsBoolean();
        }

        public static object JSEval(string strExpression)
        {
            if (jsEngine==null)
            {
                jsEngine=new Jint.Engine();
            }
            var jsValue = jsEngine.Execute(strExpression).GetCompletionValue();
            if (jsValue.IsNull() || jsValue.IsUndefined())
            {
                return null;
            }
            return jsValue.AsObject();
        }
    }

}
